package com.vert.utils;

import com.vert.annotations.RestController;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Classname FileListener
 * @Description TODO
 * @Date 2022/6/5 20:06
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class FileListener extends FileAlterationListenerAdaptor {

  /**
   * 文件创建执行
   */
  public void onFileCreate(File file) {
    System.out.println("[新建]:" + file.getAbsolutePath());
  }
  /**
   * 文件创建修改
   */
  public void onFileChange(File file) {
    String path=file.getAbsolutePath();
    System.out.println(file.getName());
    if(file.getName().contains(".jar")){
      System.out.println("加载");
      onload(path);
    }
    System.out.println("[修改]:" + file.getAbsolutePath());
  }
  /**
   * 文件删除
   */
  public void onFileDelete(File file) {
    System.out.println("[删除]:" + file.getAbsolutePath());
  }
  /**
   * 目录创建
   */
  public void onDirectoryCreate(File directory) {
    System.out.println("[新建]:" + directory.getAbsolutePath());
  }
  /**
   * 目录修改
   */
  public void onDirectoryChange(File directory) {
    String path=directory.getAbsolutePath();
    System.out.println(directory.getName());
    if(directory.getName().contains(".jar")){
      System.out.println("加载");
      onload(path);
    }
    System.out.println("[修改]:" + directory.getAbsolutePath());
  }
  /**
   * 目录删除
   */
  public void onDirectoryDelete(File directory) {
    System.out.println("[删除]:" + directory.getAbsolutePath());
  }
  public void onStart(FileAlterationObserver observer) {
    // TODO Auto-generated method stub
    super.onStart(observer);
  }
  public void onStop(FileAlterationObserver observer) {
    // TODO Auto-generated method stub
    super.onStop(observer);
  }

  public void onload(String path){
    try {
      JarScanUtils.clear();
      Set<Class<?>> cls=JarScanUtils.loadAllJarFromAbsolute(path);
      List< Class< ? >> classes = new ArrayList<>();
      for (Class< ? > c : cls) {
        classes.add(c);
      }
      addClazz(classes);
    }catch (Exception e){
      e.printStackTrace();
    }
  }

  private void addClazz(List<Class< ? >> classList){
   // RestController res=cls.getAnnotation(RestController.class);

    try {

          ObjectMaps.createClazzList(classList);
         // ObjectMaps.createClazz(cls); }
    }catch (Exception e){
      e.printStackTrace();
    }
  }


}
